/**
 * 
 */
package com.example.validation.utils;

import java.lang.reflect.Method;

/**
 * @author xiazhengjiao
 * @date 2019年5月31日
 */
public class EnumUtil {

	public static <T extends Enum<?>, S extends Enum<?>> Boolean convertEnum(Object source, Class<?> targetClass) {
		try {
			if (source instanceof Enum) {
				String sourceEnum = ((Enum<?>) source).name();
				if (getEnumObject(sourceEnum, targetClass) != null) {
					return true;
				}
			} else if (source instanceof String) {
				return toCodeDescriptionMap(source, targetClass);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	private static <T extends Enum<?>> T getEnumObject(String value, Class<?> clazz) {
		if (!clazz.isEnum()) {
			return null;
		}
		try {
			T[] enumConstants = (T[]) clazz.getEnumConstants();
			for (T ec : enumConstants) {
				if (((Enum<?>) ec).name().equals(value)) {
					return ec;
				}
			}
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static Boolean toCodeDescriptionMap(Object source, Class<?> clazz) {
		try {
			Method toName = clazz.getMethod("getMessage");
			Method toCode = clazz.getMethod("getCode");
			// 得到enum的所有实例
			Object[] objs = clazz.getEnumConstants();
			for (Object obj : objs) {
				Object code = toCode.invoke(obj);
				System.out.println(toCode.invoke(obj));
				System.out.println(toName.invoke(obj));
				if (source.equals(code.toString())) {
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
}
